//
//  SJPersonalViewController.m
//  WSL
//
//  Created by CJ on 2017/12/4.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJPersonalViewController.h"
#import "SJWordItem.h"
#import "SJExtraItem.h"
#import "SJOneCell.h"
#import "SJCustomLayout.h"
#import "SJPublishedListApi.h"
#import "SJSubscribeListApi.h"
#import "SJFollowApi.h"
#import "SJUserInfoApi.h"
#import "SJUnFollowPersonApi.h"
#import "SJFollowPersonApi.h"

#import "JTSImageViewController.h"
#import "JTSImageInfo.h"

#import <JPVideoPlayer/UIView+WebVideoCache.h>
#import <AVFoundation/AVFoundation.h>

#import "SJTreeViewController.h"
#import "SJTxtDetailViewController.h"
#import "SJFollowListViewController.h"
#import "SJUserInfoItem.h"
#import "SJPersonalHeaderView.h"

#import <ZLPhotoBrowser/ZLPhotoActionSheet.h>
#import <ZLPhotoBrowser/ZLPhotoConfiguration.h>
#import <Qiniu/QiniuSDK.h>
#import "SJGetUpTokenApi.h"

#import "SJSettingViewController.h"

@interface SJPersonalViewController () <UICollectionViewDataSource, UICollectionViewDelegate, SJCustomLayoutDelegate, JTSImageViewControllerAnimationDelegate, JPVideoPlayerDelegate, SJPersonalHeaderViewDelegate>

@property (strong, nonatomic) UIButton *searchButton;

////////////////////////////////////

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;
@property (nonatomic, assign) int currentIndex; // 发布、收藏等
@property (nonatomic, strong) SJPersonalHeaderView *header;

@property (strong, nonatomic) SJCustomLayout *customLayout;

// 视频
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) SJWordItem *selectedItem;
@property (nonatomic, strong) UIView *videoContainer;

@property (nonatomic, strong) UIImageView *detailImageView;
@property (strong, nonatomic) UILabel *detailLabel;

@property (nonatomic, strong) SJUserInfoItem *userInfo;

@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) QNUploadManager *upManager;
@property (nonatomic, strong) UIImage *uploadImage;

@end

@implementation SJPersonalViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}


- (void)dealloc {
    SJLogFunc;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (self.navigationController.childViewControllers.count > 1) {
        self.backButton.hidden = NO;
    } else {
        self.backButton.hidden = YES;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(relogin) name:SJDidLoginNotification object:nil];
    
    self.page = 0;
    [self setupUI];

    self.currentIndex = 2; // 默认发布列表
    
    [self loadNewData];
    [self getUserInfo];
}

- (void)relogin {
    [self loadNewData];
    [self getUserInfo];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (![SJUserDefaults objectForKey:SJToken]) {
        [self login];
    }
}

- (void)setupUI {
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    // 返回
    [self.view addSubview:self.backButton];
    
    if (812 == SJScreenH) {
        self.backButton.sd_layout
        .topSpaceToView(self.view, SJLayoutFrame(50))
        .leftSpaceToView(self.view, SJLayoutFrame(7))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
    } else {
        self.backButton.sd_layout
        .topSpaceToView(self.view, SJLayoutFrame(10))
        .leftSpaceToView(self.view, SJLayoutFrame(7))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
    }
    
}

#pragma mark - getter

- (UIButton *)backButton {
    
    if (!_backButton) {
        
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _backButton;
}


- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIImageView *)detailImageView{
    
    if (!_detailImageView) {
        
        _detailImageView = [UIImageView new];
        _detailImageView.image = [UIImage imageNamed:@"detail_bg_title"];
        _detailImageView.contentMode = UIViewContentModeScaleAspectFit;
        _detailImageView.alpha = 0;
        _detailImageView.userInteractionEnabled = YES;
        
        
        [_detailImageView addSubview:self.detailLabel];
        self.detailLabel.sd_layout.spaceToSuperView(UIEdgeInsetsMake(SJLayoutFrame(15), SJLayoutFrame(20), SJLayoutFrame(15), SJLayoutFrame(20)));
        
    }
    return _detailImageView;
}

- (UILabel *)detailLabel {
    
    if (!_detailLabel) {
        
        _detailLabel = [UILabel new];
        _detailLabel.textColor = SJColorHexString(@"#ffffffff");
        _detailLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(12)];
        _detailLabel.textAlignment = NSTextAlignmentLeft;
        _detailLabel.numberOfLines = 0;
        
    }
    return _detailLabel;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        
    }
    return _dataArray;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        // 首页
        self.customLayout = [[SJCustomLayout alloc] init];
        self.customLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.customLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
        [_collectionView registerClass:[SJOneCell class] forCellWithReuseIdentifier:NSStringFromClass([SJOneCell class])];
        
        [_collectionView registerClass:[SJPersonalHeaderView class] forSupplementaryViewOfKind:SJ_UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([SJPersonalHeaderView class])];
        
        // header
        _collectionView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadNewData)];
        // footer
        _collectionView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    
    return _collectionView;
}

- (void)reloadNewData {
    
    [self loadNewData];
    [self getUserInfo];
}


#pragma mark - SJCustomLayoutDelegate

- (CGRect)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout frameOfItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJWordItem *item = self.dataArray[indexPath.item];
    
    int lNum = [item.l intValue];
    int tNum = [item.t intValue];
    int wNum = [item.w intValue];
    int hNum = [item.h intValue];
    
    CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
    CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin;
    CGFloat w = wNum * SJItemWH + (wNum - 1) * SJMargin;
    CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
    
    return CGRectMake(x, y, w, h);
}

- (CGFloat)bottomMarginInCollectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout {
    
    return 80;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout heightForHeaderInSection:(NSInteger)section {
    
    return SJLayoutFrame(378);
}


#pragma mark - SJPersonalHeaderViewDelegate
- (void)personalHeaderView:(SJPersonalHeaderView *)personalHeaderView didSelectItemAtIndex:(NSInteger)index {
    
    if (index == 0) { // 关注列表
       
        SJFollowListViewController *followListVC = [SJFollowListViewController new];
        followListVC.fid = self.fid;
        followListVC.isMe = self.isMe;
        [self.navigationController pushViewController:followListVC animated:YES];
    }
    
    if (index == 1) { // 关注者列表
        
        SJFollowListViewController *followListVC = [SJFollowListViewController new];
        followListVC.fid = self.fid;
        followListVC.isMe = self.isMe;
        followListVC.isFollowed = YES;
        [self.navigationController pushViewController:followListVC animated:YES];
    }
    
    if (index == 2) { // 发布列表（默认）
        
        self.currentIndex = 2;
        [self loadNewData];
    }
    
    if (index == 3) { // 收藏列表
        
        if (!self.isMe) {
            return;
        }
        
        self.currentIndex = 3;
        [self loadNewData];
    }
    
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:SJ_UICollectionElementKindSectionHeader]) {
        
        SJPersonalHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:SJ_UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([SJPersonalHeaderView class]) forIndexPath:indexPath];
        
        header.userInfo = self.userInfo;
        header.isMe = self.isMe;
        header.delegate = self;
        
        WeakSelf;
        header.avatarTap = ^(NSString *str) {
            [weakSelf cameraAction:@"1"];
            
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            attributes[@"name"] = @"设置头像";
            [SJStatisticTool event:@"setAvatar" attributes:attributes];
        };
        
        
        header.coverTap = ^(NSString *str) {
            [weakSelf cameraAction:@"3"];
            
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            attributes[@"name"] = @"设置封面";
            [SJStatisticTool event:@"setCover" attributes:attributes];
        };
        
        header.settingTap = ^(NSString *str) {
            
            SJSettingViewController *settingVC = [SJSettingViewController new];
            [weakSelf.navigationController pushViewController:settingVC animated:YES];
        };
        
        header.followTap = ^(UIButton *btn) { // 关注
            [weakSelf followAction:btn];
            
        };
        
        self.header = header;
        
        return header;
        
    } else if ([kind isEqualToString:SJ_UICollectionElementKindSectionFooter]){
        
        return nil;
    }
    
    return nil;
}

- (void)followAction:(UIButton *)button {

    if ([self.userInfo.is_follow isEqualToString:@"2"]) { // 已关注，取消

        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
        parameters[@"fid"] = self.userInfo.ID;

        SJUnFollowPersonApi *api = [[SJUnFollowPersonApi alloc] initWithParameters:parameters];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {

            if ([api.responseObject[@"result"][@"err"] intValue] == 0) {

                button.selected = NO;
                self.userInfo.is_follow = @"1";
            }

        } failure:^(YTKBaseRequest *request) {

        }];

    } else {

        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
        parameters[@"fid"] = self.userInfo.ID;

        SJFollowPersonApi *api = [[SJFollowPersonApi alloc] initWithParameters:parameters];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {

            if ([api.responseObject[@"result"][@"err"] intValue] == 0) {

                button.selected = YES;
                self.userInfo.is_follow = @"2";
            }

        } failure:^(YTKBaseRequest *request) {

        }];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.collectionView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJOneCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJOneCell class]) forIndexPath:indexPath];
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    cell.item = item;
    
    if (cell.hidden) {
        cell.hidden = NO;
    }
    
    WeakSelf;
    cell.singleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf singleTap:cell];
    };
    
    cell.doubleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf doubleTap:cell];
    };
    
    return cell;
}

#pragma mark 点击 cell 的事件
- (void)doubleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"1"]) { // 文字
        
        [self tapText:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
        
        [self tapPic:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
        
        [self tapAudio:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"音频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Audio" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
        
        [self tapVideo:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"视频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Video" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
        
        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
        txtVC.item = item;
        [self.navigationController pushViewController:txtVC animated:YES];
    }
    
    
//    if ([item.fmt isEqualToString:@"1"]) {
//
//        self.selectedItem = item;
//        [self tapText:(SJOneCell *)cell item:item];
//    } else {
//
//        SJTreeViewController *treeVC = [SJTreeViewController new];
//        treeVC.item = item;
//
//        if (self.currentIndex == 2) { // 发布列表
//            treeVC.pageType = @"user_published";
//        } else if (self.currentIndex == 3) { // 收藏列表
//            treeVC.pageType = @"user_fav";
//        }
//
//        [self.navigationController pushViewController:treeVC animated:YES];
//
//    }
    
}

- (void)singleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    
    SJTreeViewController *treeVC = [SJTreeViewController new];
    treeVC.item = item;
    
    if (self.currentIndex == 2) { // 发布列表
        treeVC.pageType = @"user_published";
    } else if (self.currentIndex == 3) { // 收藏列表
        treeVC.pageType = @"user_fav";
    }
    
    [self.navigationController pushViewController:treeVC animated:YES];
    
    
//    self.selectedItem = item;
//    
//    if ([item.fmt isEqualToString:@"1"]) { // 文字
//        
//        SJTreeViewController *treeVC = [SJTreeViewController new];
//        treeVC.item = item;
//        
//        if (self.currentIndex == 2) { // 发布列表
//            treeVC.pageType = @"user_published";
//        } else if (self.currentIndex == 3) { // 收藏列表
//            treeVC.pageType = @"user_fav";
//        }
//        
//        [self.navigationController pushViewController:treeVC animated:YES];
//        
//    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
//        
//        [self tapPic:(SJOneCell *)cell item:item];
//        
//    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
//        
//        [self tapAudio:(SJOneCell *)cell item:item];
//        
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"音频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Audio" attributes:attributes];
//        
//    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
//        
//        [self tapVideo:(SJOneCell *)cell item:item];
//        
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"视频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Video" attributes:attributes];
//        
//    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
//        
//        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
//        txtVC.item = item;
//        [self.navigationController pushViewController:txtVC animated:YES];
//    }
//    
}

- (void)tapAudio:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    SJExtraItem *extra = [SJExtraItem modelWithJSON:item.extra];
    
    if (extra.cover) {
        NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, extra.cover];
        imageInfo.imageURL = [NSURL URLWithString:urlString];
    } else {
        UIImage *img = [UIImage imageNamed:@"icn_audio"];
        imageInfo.image = img;
        imageInfo.referenceContentMode = UIViewContentModeCenter;
    }
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    self.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:urlString]];
    [self.player play];
}


- (void)tapVideo:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceContentMode = UIViewContentModeCenter;
    UIImage *img = [UIImage imageNamed:@"common_trans_square"];
    
    imageInfo.image = img;
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
    // 视频
    [[JPVideoPlayerCache sharedCache] clearDiskOnCompletion:^{
        // do something  必须清了缓存？才能播放？
    }];
    
    self.videoContainer = ({
        UIView *videoView = [UIView new];
        videoView.backgroundColor = [UIColor blackColor];
        videoView.frame = CGRectMake(0, 0, SJScreenW, SJScreenW * 9.0 / 16.0);
        [imageViewer.imageView addSubview:videoView];
        
        videoView;
    });
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self.videoContainer addGestureRecognizer:tapGestureRecognizer];
    self.videoContainer.jp_videoPlayerDelegate = self;
    [self.videoContainer jp_perfersPlayingProgressViewColor:SJColorHexString(@"#f76a4a")];
    [self.videoContainer jp_perfersDownloadProgressViewColor:[UIColor lightGrayColor]];
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    [self.videoContainer jp_playVideoWithURL:[NSURL URLWithString:urlString]];
    
}

- (void)tapText:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = item.content;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 0;
    titleLabel.size_sd = CGSizeMake(SJScreenW - SJLayoutFrame(40), SJScreenH);
    
    UIImage *img = [titleLabel.layer snapshotImage];
    while (!img) { // 这样好吗？
        img = [titleLabel.layer snapshotImage];
    }
    
    imageInfo.image = img;
    
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
}

- (void)tapPic:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, item.content];
    imageInfo.imageURL = [NSURL URLWithString:urlString];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceCornerRadius = 6;
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
}

#pragma mark - JPVideoPlayerDelegate

- (BOOL)shouldDownloadVideoForURL:(NSURL *)videoURL{
    return YES;
}

- (BOOL)shouldProgressViewOnTop{
    return NO;
}

- (BOOL)shouldAutoReplayAfterPlayCompleteForURL:(nonnull NSURL *)videoURL {
    
    return YES;
}

- (void)playingStatusDidChanged:(JPVideoPlayerPlayingStatus)playingStatus{
    
    SJLog(@"playingStatus-----%ld", (long)playingStatus);
    
}

//- (void)downloadingProgressDidChanged:(CGFloat)downloadingProgress{
//    SJLog(@"downloadingProgress------%0.2lf", downloadingProgress);
//}
//
//- (void)playingProgressDidChanged:(CGFloat)playingProgress{
//    SJLog(@"playingProgress------%0.2lf", playingProgress);
//}

#pragma mark - Tap Event

- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusPortrait) {
            [self.videoContainer jp_gotoLandscapeAnimated:YES completion:^{
            }];
        }
        else if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusLandscape) {
            [self.videoContainer jp_gotoPortraitAnimated:YES completion:^{
            }];
        }
        
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}

#pragma JTSImageViewControllerAnimationDelegate

- (void)imageViewerWillBeginPresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView {
    
}

- (void)imageViewerWillAnimatePresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration { // 显示完 图片墙 did
    
    WeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf showDetaillInView:containerView];
    });
    
    
}

- (void)imageViewer:(JTSImageViewController *)imageViewer willAdjustInterfaceForZoomScale:(CGFloat)zoomScale withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
}

- (void)imageViewerWillBeginDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView { // 将要消失 图片墙 will
    
    // 删除详情
    [self hideDetaill];
    
    if ([self.selectedItem.fmt isEqualToString:@"4"]) {
        
        [self.videoContainer jp_stopPlay];
        [self.videoContainer removeFromSuperview];
        self.videoContainer = nil;
    }
    
    if ([self.selectedItem.fmt isEqualToString:@"3"]) {
        
        [self.player pause];
        self.player = nil;
    }
}

- (void)imageViewerWillAnimateDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
    
}


- (void)showDetaillInView:(UIView *)view {
    
    [view addSubview:self.detailImageView];
    self.detailImageView.sd_layout
    .heightIs(SJLayoutFrame(80))
    .leftSpaceToView(view, SJLayoutFrame(0))
    .rightSpaceToView(view, SJLayoutFrame(0))
    .bottomSpaceToView(view, SJLayoutFrame(0));
    
    SJExtraItem *extraItem = [SJExtraItem modelWithJSON:self.selectedItem.extra];
    self.detailLabel.text = extraItem.t;
    
    if (![extraItem.t isNotBlank]) {
        self.detailImageView.hidden = YES;
    }
    
    [UIView animateWithDuration:.25 animations:^{
        self.detailImageView.alpha = 1;
    }];
    
}

- (void)hideDetaill {
    
    [self.detailImageView removeAllSubviews];
    [self.detailImageView removeFromSuperview];
    self.detailImageView = nil;
    self.detailLabel = nil;
    
}

#pragma mark - request

- (void)loadNewData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = @"0";
    
    if (!self.isMe) {
        parameters[@"fid"] = self.fid;
    }
    
    SJRequest *api = nil;
    
    if (self.currentIndex == 2) { // 发布列表
        api = [[SJPublishedListApi alloc] initWithParameters:parameters];
    } else if (self.currentIndex == 3) { // 收藏列表
        api = [[SJSubscribeListApi alloc] initWithParameters:parameters];
    }
    

//    if ([api loadCacheWithError:nil]) {
//
//        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
//            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
//            self.page = [api.responseObject[@"content"][@"cur"] intValue];
//
//            [self async];
//        } else {
//            [self.dataArray removeAllObjects];
//        }
//    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
            [self async];
            
        } else {
            [self.dataArray removeAllObjects];
            [self.collectionView reloadData];
            [self.collectionView.mj_header endRefreshing];
        }
        
        [self renderHeader];
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    }];
    
}

- (void)loadMoreData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    
    if (!self.isMe) {
        parameters[@"fid"] = self.fid;
    }
    
    SJRequest *api = nil;
    
    if (self.currentIndex == 2) { // 发布列表
        api = [[SJPublishedListApi alloc] initWithParameters:parameters];
    } else if (self.currentIndex == 3) { // 收藏列表
        api = [[SJSubscribeListApi alloc] initWithParameters:parameters];
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
            [self async];
            
        } else {
            self.page--;
            [self.collectionView reloadData];
            [self.collectionView.mj_footer endRefreshing];
        }
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        self.page--;
    }];
}

- (void)async {
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        
        [self getItemOrigin];
        
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        dispatch_async(mainQueue, ^{
            
            [self.collectionView reloadData];
            [self.collectionView.mj_footer endRefreshing];
            [self.collectionView.mj_header endRefreshing];
            
        });
    });
}

- (void)renderHeader {
    
    for (UIView *viewP in self.header.numberBar.subviews) {
        
        if (viewP.tag == self.currentIndex) {
            for (UIView *view in viewP.subviews) {
                if ([view isKindOfClass:[UILabel class]]) {
                    UILabel *l = (UILabel *)view;
                    l.textColor = SJColorHexString(@"#99c7ff");
                }
            }
        } else {
            for (UIView *view in viewP.subviews) {
                if ([view isKindOfClass:[UILabel class]]) {
                    UILabel *l = (UILabel *)view;
                    l.textColor = SJColorHexString(@"#ffffff");
                }
            }
        }
    }
    
    if (!self.isMe) {
        UIView *viewP = self.header.numberBar.subviews.lastObject;
        
        for (UIView *view in viewP.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                UILabel *l = (UILabel *)view;
                l.textColor = SJColorHexString(@"#9a9a9a");
            }
        }
    }
}


- (void)getItemOrigin {
    
    // 初始化二维数组
    NSMutableArray *grid = [NSMutableArray array];
    int max_t = (int)self.dataArray.count * SJItemCount;
    int max_w = SJItemCount;
    for (int i = 0; i < max_t; i++) {
        NSMutableArray *arrl = [NSMutableArray array]; //横向
        [grid addObject:arrl];
        for (int j = 0; j < max_w; j++) {
            grid[i][j] = @0;
        }
    }
    
    // 为每个 item 设置 l、t。
    for (SJWordItem *item in self.dataArray) {
        
        int w = [item.w intValue];
        int h = [item.h intValue];
        
        NSMutableDictionary *dict = [self calLTWithW:w h:h grid:grid];
        
        if (dict != nil) {
            item.l = dict[@"l"];
            item.t = dict[@"t"];
        }
    }
}

- (NSMutableDictionary *)calLTWithW:(int)w h:(int)h grid:(NSMutableArray *)grid {
    
    int max_t = (int)grid.count;
    int max_w = SJItemCount;
    
    for (int i = 0; i < max_t; i++) {
        for (int j = 0; j < max_w; j++) {
            
            BOOL find = NO;
            if ([grid[i][j] isEqualToNumber:@0] && j + w <= max_w) {
                for (int m = 0; m < h; m++) {
                    for (int n = 0; n < w; n++) {
                        if ([grid[i + m][j + n] isEqualToNumber:@1]) {
                            find = YES;
                            break;
                        }
                    }
                    if (find) {
                        break;
                    }
                }
                
                if (!find) {
                    
                    NSMutableDictionary *dict =  [NSMutableDictionary dictionary];
                    dict[@"t"] = @(i);
                    dict[@"l"] = @(j);
                    
                    for (int m = 0; m < h; m++) {
                        for (int n = 0; n < w; n++) {
                            grid[i + m][j + n] = @1;
                        }
                    }
                    
                    return dict;
                }
            }
        }
    }
    return nil;
}


/**
 获取用户信息
 */
- (void)getUserInfo {
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    
    if (!self.isMe) {
        parameters[@"fid"] = self.fid;
    }
    
    SJUserInfoApi *api = [[SJUserInfoApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                
        self.userInfo = [SJUserInfoItem modelWithJSON:api.responseObject[@"content"]];
        [self.collectionView reloadData];
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}


- (void)cameraAction:(NSString *)type { // 进入相册
    
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    
    //以下参数为自定义参数，均可不设置，有默认值
    actionSheet.configuration.allowSelectImage = YES;
    actionSheet.configuration.allowSelectGif = NO;
    actionSheet.configuration.allowSelectVideo = NO;
    actionSheet.configuration.allowSelectLivePhoto = YES;
    actionSheet.configuration.allowForceTouch = NO;
    actionSheet.configuration.allowEditImage = YES;
    actionSheet.configuration.allowEditVideo = YES;
    actionSheet.configuration.allowSlideSelect = NO;
    actionSheet.configuration.allowMixSelect = NO;
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = YES;
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = YES;
    //设置照片最大预览数
    actionSheet.configuration.maxPreviewCount = 0;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    //单选模式是否显示选择按钮
    actionSheet.configuration.showSelectBtn = NO;
    actionSheet.configuration.saveNewImageAfterEdit = NO;
    //是否在选择图片后直接进入编辑界面
    actionSheet.configuration.editAfterSelectThumbnailImage = YES;
    actionSheet.configuration.navBarColor = SJColorHexString(@"#00000090");
    actionSheet.configuration.bottomViewBgColor = SJColorHexString(@"#00000090");
    
    if ([type isEqualToString:@"1"]) { // 头像
        
        //设置编辑比例
        actionSheet.configuration.clipRatios = @[GetClipRatio(1, 1)];
        
    } else if ([type isEqualToString:@"3"]) { // 封面
        
//        CGFloat h = SJItemWH * 6 + SJMargin * 5;
//        CGFloat w = SJItemWH * 8 + SJMargin * 7;
        //设置编辑比例
        actionSheet.configuration.clipRatios = @[GetClipRatio(4, 3)];
        
    }
    WeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        weakSelf.uploadImage = [images lastObject];
        [weakSelf uploadImageToQNFilePath:[weakSelf getImagePath:weakSelf.uploadImage] type:type];
    }];
    
    //调用相册
    [actionSheet showPhotoLibraryWithSender:self];
    
}

/**
 七牛
 */
- (QNUploadManager *)upManager{
    
    if (!_upManager) {
        //华北
        QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
            builder.zone = [QNFixedZone zone1];
        }];
        _upManager = [[QNUploadManager alloc] initWithConfiguration:config];
    }
    return _upManager;
}

//照片获取本地路径转换
- (NSString *)getImagePath:(UIImage *)Image {
    
    NSString *filePath = nil;
    NSData *data = nil;

    data = [UIImage dataCompressImageQuality:Image toByte:200 * 1024];
    
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //把刚刚图片转换的data对象拷贝至沙盒中
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *ImagePath = [[NSString alloc] initWithFormat:@"/userHeader.png"];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];
    
    //得到选择后沙盒中图片的完整路径
    filePath = [[NSString alloc] initWithFormat:@"%@%@", DocumentsPath, ImagePath];
    return filePath;
}

/**
 上传七牛
 
 @param filePath 图片路径
 */
- (void)uploadImageToQNFilePath:(NSString *)filePath type:(NSString *)type{
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
    [SVProgressHUD showWithStatus:@"正在修改..."];
    
    SJUserInfoItem *myInfo = [SJUserInfoItem modelWithJSON:[SJUserDefaults objectForKey:SJUserInfo]];
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"type"] = type;
    parameters[@"id"] = myInfo.ID;
    
    SJGetUpTokenApi *api = [[SJGetUpTokenApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            NSString *uploadToken = [NSString stringWithFormat:@"%@",api.responseObject[@"content"][@"uptoken"]];
            NSString *key = [NSString stringWithFormat:@"%@",api.responseObject[@"content"][@"key"]];
            [self.upManager putFile:filePath key:key token:uploadToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                
                if (info.isOK) {
                    
                    [self getUserInfo];
                    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
                    [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                    });
                    
                } else {
                    
                    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
                    [SVProgressHUD showErrorWithStatus:@"修改失败"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                    });
                }
            } option:nil];
            
        } else {
            
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
            [SVProgressHUD showErrorWithStatus:@"修改失败"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
        }
        
    } failure:^(YTKBaseRequest *request) {
    }];
}


#pragma mark - 登录
- (void)login {
    
    // 进入到登录注册界面
    SJRegisterViewController *registerVC = [SJRegisterViewController new];
    SJNavigationController *registerlNav = [[SJNavigationController alloc] initWithRootViewController:registerVC];
    [self presentViewController:registerlNav animated:YES completion:nil];
}

@end

